//
//  NewsflashRecommendDetail.m
//  AutoHome
//
//  Created by wqh on 15-5-15.
//  Copyright (c) 2015年 Wqh. All rights reserved.
//

#import "NewsflashRecommendDetail.h"
#import "NewsFlashHeaderView.h"
#import "NewsflashDetailModel.h"
#import "NewsflashRecommendDetailCell.h"

@interface NewsflashRecommendDetail ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@property (nonatomic) NewsFlashHeaderView *headerView;
@property (nonatomic) NSMutableDictionary *newsdataDict;
@property (nonatomic) NSMutableDictionary *articlemodelDict;
@property (nonatomic) NSMutableArray *dataArr;
@end

@implementation NewsflashRecommendDetail

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.view.backgroundColor = [UIColor blackColor];
    
    [self createButton];
    [self createTableHeaderView];
    [self createTableView];
    [self downloadData];
  
}

#pragma mark -showUI

- (void)createButton {
    UIButton *backBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    backBtn.backgroundColor = [UIColor blackColor];
    [backBtn setImage:[UIImage imageNamed:@"bar_btn_icon_returntext_white"] forState:UIControlStateNormal];
    
    [backBtn addTarget:self action:@selector(backClick:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.frame = CGRectMake(10, 25, 40, 25);
    [self.view addSubview:backBtn];
}

- (void)backClick:(UIButton*)button {
    [self.navigationController popViewControllerAnimated:YES];
}

//创建滚动视图的头视图
- (void)createTableHeaderView {
    self.headerView = [[[NSBundle mainBundle] loadNibNamed:@"NewsFlashHeaderView" owner:self options:nil] lastObject ];
    self.headerView.frame = CGRectMake(0, -80, kScreenWidth, 40);
}

- (void)createTableView {
    
    self.bgImageView.frame = CGRectMake(0, -100, self.tableView.frame.size.width, 200);
    [self.tableView addSubview:self.bgImageView];
    
    [self.tableView addSubview:self.headerView   ];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
    self.tableView.contentInset = UIEdgeInsetsMake(200, 0, 0, 0);
}

- (void)downloadData {
    [[DataEngine sharedInstance] requestNewsflahDetailDataWithId:self.model.id success:^(id respondsData) {
        [self downloadDataSuccess:respondsData];
    } failed:^(NSError *error) {
        
    }];
}

- (void)downloadDataSuccess:(id)respondsData {
    
    self.dataArr = [NSMutableArray array];
    NSDictionary *dict = [NSJSONSerialization JSONObjectWithData:respondsData options:NSJSONReadingMutableContainers error:nil];
    
    self.newsdataDict = dict[@"result"][@"newsdata"];
    
    self.articlemodelDict = dict[@"result"][@"articlemode"];
    
    [self reloadHeaderView];
 
    for (NSDictionary *messageDict in dict[@"result"][@"messagelist"]) {
      
        NewsflashDetailModel *model = [NewsflashDetailModel new];
        [model setValuesForKeysWithDictionary:messageDict];
        [self.dataArr addObject:model];
    }

    [self.tableView reloadData];
    
}

- (void)reloadHeaderView {
    [self.bgImageView sd_setImageWithURL:[NSURL URLWithString:self.newsdataDict[@"img"]] placeholderImage:[UIImage imageNamed:@"black_default_640_320"]];
    [self.headerView showDataWithDict:self.newsdataDict];
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
        static NSString *cellid = @"cellID";
        NewsflashRecommendDetailCell *cell = [tableView dequeueReusableCellWithIdentifier:cellid];
        if (!cell) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"NewsflashRecommendDetailCell" owner:self options:nil] lastObject];
        }
   
        [cell showDataWithModel:self.dataArr[indexPath.row]];
        return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    
    NewsflashDetailModel *model = self.dataArr[indexPath.row];
    
    //从contentlabel 的y 左边开始计算 所有label 的y坐标都是59；
    CGFloat y = 59;
    
    //计算label内容高
    CGFloat contentHeight = [self textHeightFromTextString:model.content width:kScreenWidth-20 fontSize:14];
  
    if (model.attachments.count > 0) {
        y = y+contentHeight + 12;
        
        //计算图片数组的高度
        CGFloat picsHeight  = 0;
        for (NSDictionary *picInfo in model.attachments) {
            CGFloat pic_height = 300*[picInfo[@"height"] floatValue] /[picInfo[@"width"] floatValue];
            picsHeight += pic_height +10;
        }
        
        y += picsHeight;
       
        return y+20;
    }else {

        return y + contentHeight + 50;
    }

}

//动态计算行高
- (CGFloat)textHeightFromTextString:(NSString *)text width:(CGFloat)textWidth fontSize:(CGFloat)size{
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] >= 7.0) {
        //iOS7之后
        /*
         第一个参数: 预设空间 宽度固定  高度预设 一个最大值
         第二个参数: 行间距 如果超出范围是否截断
         第三个参数: 属性字典 可以设置字体大小
         */
        NSDictionary *dict = @{NSFontAttributeName:[UIFont systemFontOfSize:size]};
        CGRect rect = [text boundingRectWithSize:CGSizeMake(textWidth, MAXFLOAT) options:NSStringDrawingTruncatesLastVisibleLine|NSStringDrawingUsesFontLeading|NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil];
        //返回计算出的行高
        return rect.size.height;
        
    }else {
        //iOS7之前
        /*
         1.第一个参数  设置的字体固定大小
         2.预设 宽度和高度 宽度是固定的 高度一般写成最大值
         3.换行模式 字符换行
         */
        CGSize textSize = [text sizeWithFont:[UIFont systemFontOfSize:size] constrainedToSize:CGSizeMake(textWidth, MAXFLOAT) lineBreakMode:NSLineBreakByCharWrapping];
        return textSize.height;//返回 计算出得行高
    }
}

#pragma mark - ScrollViewDelegate
- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    CGFloat yOffset  = scrollView.contentOffset.y;
 
    if (yOffset < -100) {
        CGRect f = self.bgImageView.frame;
        f.origin.y = yOffset;
        f.size.height =  -yOffset;
        self.bgImageView.frame = f;
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
